/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package utilities;

import resource.Macro;

/**
 *
 * @author fangchengjia
 */
public class Validation {
    public static boolean checkDate(String date) {
        int[] num_day = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
        int year = Integer.parseInt(date.split("-")[0]);
        int month = Integer.parseInt(date.split("-")[1]);
        int day = Integer.parseInt(date.split("-")[2]);
        if (year % 4 == 0) {
            num_day[1] = 29;
        }
        if (month > 12 || month <= 0) { return false; }
        return day <= num_day[month - 1] && day > 0;
    }
    
    public static boolean empty(String index, String value){
        if (value.isEmpty()){
            Prompt.warning(Macro.WARNING_EMPTY, index);
            return true;
        }
        return false;
    }
    
    public static boolean validFormat(String index, String value,
            String format, String expect){
        if (empty(index, value)){
            return false;
        }
        if (!value.matches(format)){
            Prompt.warning(Macro.WARNING_FORMAT, index, expect);
            return false;
        }
        return true;
    }
    
    public static boolean validDate(String index, String value,
            String format, String expect){
        if (!validFormat(index, value, format, expect)){
            return false;
        }
        if (!checkDate(value)){
            Prompt.warning(Macro.WARNING_INVALID, index);
            return false;
        }
        return true;
    }
    
    public static boolean valideRecord(DBConnector db, String table,
            String item, String value){
        if (!db.check(table, String.format("%s='%s'", item,
                Codecs.encode(value)))){
            Prompt.warning(String.format(
                    "The value %s:%s does not exist in table %s.",
                    item, value, table));
            return false;
        }
        return true;
    }
}
